#! /usr/bin/perl -w

use strict;

use CGI::FOGE2::Test;
use HTML::TokeParser;
use WWW::Mechanize;

# args of a testNN.pl program:
# name of the CGI script to call "http://.../testNN.cgi"
# name "testNN"
# logfile (will be opened in append mode)

my ($url, $testname, $flog) = @ARGV;

open FLOG, ">>$flog" 
    || die "Can't open $flog for appending: $!";

my $ag = WWW::Mechanize->new();
my $tst = CGI::FOGE2::Test->new($testname, \*FLOG);
printf "Testing script at \`%s'\n", $url;
my $res;

# data to send and expected results
my $answers =
    {
     bad  =>      [ 3, [q00 => 'bad'],       10.34],
     okay =>      [ 4, [q00 => 'okay'],      13.79],
     good =>      [12, [q00 => 'good'],      41.37],
     excellent => [10, [q00 => 'excellent'], 34.48],
    };

# send test data (...)
foreach my $item (values %$answers) {
    my $times = $item->[0];
    my $i;
    for ($i=0; $i<$times; ++$i) {
        $tst->testname("Retrieve($i)");
        $ag->get($url);
        $tst->testresult($ag->status() == 200, 1);

        $tst->testname("Get form 1 ($i)");
        $res= $ag->form(1);
        $tst->testresult($res,1);

	my %hash = @{$item->[1]};
        foreach my $field (keys %hash) {
            $tst->testname("Fill field 1 ($i)");
            $ag->field($field, $hash{$field});
            $tst->testresult(1, 0);
        }

        $tst->testname("Click($i)");
        $tst->testresult(defined $ag->click(), 1);

#        print "sleeping...\r" if $isatty;
#        sleep 1;
    }
}

# retrieve the stats page
my $htp = HTML::TokeParser->new(\$ag->{content});

$tst->testname("RetrieveStats");
$ag->get($url."?action=see");
$tst->testresult($ag->status() == 200, 1);

{
    $tst->testname("GetTable0Row0");
    $htp->get_tag('table');
    $tst->testresult(defined($htp->get_tag('table')));

    my $table0 = $tst->html_to_array($htp);

    print FLOG $tst->table_to_string($table0), "\n";

    # in this simple form, we have names // frequencies // relative frequencies

    my ($names, $freq, $relfreq) = 
	($table0->[0], $table0->[1], $table0->[2]);

    for (my $idx = 1; $idx < scalar @{$table0->[0]}; ++$idx) {

#    if (defined $table0->[0]->[0] && $table0->[0]->[0] =~
 
	my ($fieldname, $pcent, $nb, $total);
    $tst->testname("Table0Line0Format", 1);
    
	$fieldname = $names->[$idx];
	$nb        = $freq->[$idx];

	if ($relfreq->[$idx] =~ /(\d+(?:.\d+))%/) {
	    $pcent = $1;
	    $tst->testresult(1);
	} else {
	    $pcent = undef;
	    $tst->testresult(0);
	}

	

        $tst->testname("Table0Line0Name", 0);
	my $values = $answers->{$fieldname};
        $tst->testresult(defined $values);
        $tst->testname("Table0Line0Pcent", 0);
        $tst->testresult($tst->eqtol($pcent, $values->[2], 1.00));
        $tst->testname("Table0Line0Freq", 0);
        $tst->testresult($nb     == $values->[0]);
    }
}

$tst->finish();
